from app import db
from datetime import datetime

class Menu(db.Model):
    """菜单模型"""
    __tablename__ = 'menus'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False, index=True)
    code = db.Column(db.String(80), unique=True, nullable=False, index=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('menus.id'))
    path = db.Column(db.String(255))  # 路由路径
    component = db.Column(db.String(255))  # 组件路径
    redirect = db.Column(db.String(255))  # 重定向路径
    icon = db.Column(db.String(100))  # 图标
    title = db.Column(db.String(100))  # 菜单标题
    hidden = db.Column(db.Boolean, default=False)  # 是否隐藏
    sort_order = db.Column(db.Integer, default=0)  # 排序
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 自关联
    children = db.relationship('Menu', backref=db.backref('parent', remote_side=[id]))
    
    def __repr__(self):
        return f'<Menu {self.name}>'
    
    def to_dict(self, include_children=True):
        """转换为字典，可选择是否包含子菜单"""
        result = {
            'id': self.id,
            'name': self.name,
            'code': self.code,
            'parent_id': self.parent_id,
            'path': self.path,
            'component': self.component,
            'redirect': self.redirect,
            'icon': self.icon,
            'title': self.title,
            'hidden': self.hidden,
            'sort_order': self.sort_order,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }
        
        if include_children and self.children:
            result['children'] = [child.to_dict(include_children=True) for child in self.children]
        else:
            result['children'] = []
            
        return result
    
    def to_tree_dict(self):
        """转换为树形结构，只返回顶级菜单"""
        if self.parent_id is None:
            # 这是顶级菜单，包含所有子菜单
            return self.to_dict(include_children=True)
        else:
            # 这是子菜单，不单独返回
            return None 